#pragma once

#include<iostream>
#include<list>
#include<vector>
#include<algorithm>

using namespace std;

namespace stl
{
	template<class T>
	struct list_node
	{
		list_node<T>* _next;
		list_node<T>* _prev;
		T _val;

		list_node(const T& val = T())
			: _next(nullptr)
			, _prev(nullptr)
			, _val(val)
		{ }
	};



	//typedef list_iterator<T, T&, T*> iterator;
	//typedef list_iterator<T, const T&, const T*> iterator;
	template<class T, class Ref, class Ptr>
	struct list_iterator
	{
		typedef list_node<T> Node;
		typedef list_iterator<T, Ref, Ptr> self;
		typedef list_iterator<T, const T&, const T*> const_iterator;
		typedef list_iterator<T, T&, T*> iterator;
		Node* _node;

		list_iterator(Node* node)
			:_node(node)
		{ }


		Ref operator*()
		{
			return _node->_val;
		}

		Ptr operator->()
		{
			return &_node->_val;
		}

		self& operator++()
		{
			_node = _node->_next;
			return *this;
		}

		self operator++(int)
		{
			self tmp = *this;
			*this = *this->nevt;
			return tmp;
		}

		self& operator--()
		{
			_node = _node->_prev;
			return *this;
		}

		self operator--(int)
		{
			Node* tmp = _node;
			_node = _node->prev;
			return *tmp;
		}

		bool operator!=(const self& it) const
		{
			return _node != it._node;
		}

		bool operator==(const self& it) const
		{
			return _node == it._node;
		}
	};

	template<class T>
	class list
	{
		typedef list_node<T> Node;
		typedef list_iterator<T, T&, T*> iterator;
		typedef list_iterator<T, const T&, const T*> const_iterator;

	public:
		list()
		{
			_head = new Node;
			_head->_prev = _head;
			_head->_next = _head;
		}

		void push_back(const T& p)
		{
			Node* tail = _head->_prev;
			Node* newnode = new Node(p);

			tail->_next = newnode;
			newnode->_prev = tail;
			newnode->_next = _head;
			_head->_prev = newnode;
		}

		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

		void print(const list<T>& n)
		{
			auto it = begin();
			while (it != end())
			{
				cout << *it << " ";
				++it;
			}
			cout << endl;
		}

		iterator insert(iterator pos, const T& n)
		{
			Node* newnode = new Node(n);
			Node* onode = pos._node;
			Node* oprev = pos._node->_prev;

			newnode->_prev = oprev;
			oprev->_next = newnode;
			newnode->_next = onode;
			onode->_prev = newnode;
			return onode;
		}

		iterator erase(iterator pos)
		{
			Node* denode = pos._node;
			Node* oprev = denode->_prev;
			Node* onext = denode->_next;

			oprev->_next = onext;
			onext->_prev = oprev;
			return onext;
		}

		~list()
		{
			iterator it = begin();
			while (it != end())
			{
				Node* tmp = it._node;
				++it;
				delete tmp;
			}
			delete _head;
			_head = nullptr;
		}
	private:
		Node* _head;
	};
}


